import React from 'react';
import { connect } from 'react-redux';
import { Form, Input, Button, DatePicker, Select, message } from 'antd';
import moment from 'moment';
import contractService from 'containers/approve/contract/contract.service';
import SelectEmployeeGroup from 'components/template/select-employee-group';
import 'styles/receipt-type-setting/contract-type-define/new-contract-type.scss';
import { messages } from 'share/common';
import Chooser from 'components/chooser';

const FormItem = Form.Item;
const Option = Select.Option;

class NewContractType extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      fetching: false,
      isEnabled: true,
      employeeDisabled: true,
      startValue: null,
      endValue: null,
      setOfBooksOptions: [],
      contractCategory: [],
      partner: {
        disabled: true
      },
      headerData: {},
      partnerCategoryOptions: [],
      formTypeOptions: [],
      radioValue: 'all',
      showSelectEmployeeGroup: false,
      chosenEmployeeIDs: [],
      editTag: false,
    };
  }


  componentWillReceiveProps(nextProps) {
    if (!this.props.params.flag && nextProps.params.flag) {
      let headerData = { ...nextProps.params.contractHead };
      // headerData.partnerId = { value: headerData.partnerId, label: headerData.partnerName };
      this.setState({
        headerData,
        employeeDisabled: !headerData.unitId
      });
    }
    if (this.props.params.flag && !nextProps.params.flag) {
      this.setState({
        headerData: {},
        endValue: null,
        startValue: null
      });
      this.props.form.resetFields();
    }
  }

  getContractType = () => {
    this.getSystemValueList(2107)
      .then(res => { //合同方类型
        let partnerCategoryOptions = res.data.values || [];
        this.setState({ partnerCategoryOptions });
      });
  };

  //新建保存
  handleSave = (e) => {
    e.preventDefault();
    const { headerData } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({ loading: true });
        values.id = this.state.headerData.id;
        values.versionNumber = this.state.headerData.versionNumber;
        values.contractTypeId = this.state.headerData.contractTypeId;
        values.signDate = values.signDate && values.signDate.format('YYYY-MM-DD');
        values.startDate = values.startDate && values.startDate.format('YYYY-MM-DD');
        values.endDate = values.endDate && values.endDate.format('YYYY-MM-DD');
        if (!values.startDate) {
          values.startDate = '';
        }
        if (!values.endDate) {
          values.endDate = '';
        }
        values.companyId = this.state.headerData.companyId;
        values.unitName = headerData.unitId && headerData.unitId[0] && headerData.unitId[0].name || '';
        values.unitId = headerData.unitId && headerData.unitId[0] && headerData.unitId[0].departmentId || '';
        values.partnerCategory = values.partnerCategory.key;
        values.partnerId = headerData.partnerId;
        values.partnerName = headerData.partnerName;
        values.employee = headerData.userName;
        values.employeeId = headerData.employeeId;
        values.contractCategory = this.state.headerData.contractCategory;
        values.remark = this.state.headerData.remark;
        let method = null;
        let flag = false;
        if (this.state.headerData.id) {
          method = contractService.updateEditInfoContractHeader;
          values.id = this.state.headerData.id;
          flag = true;
        } else {
          method = contractService.addContractInfo;
        }
        method(values)
          .then(res => {
            if (res.status === 200) {
              this.setState({ loading: false });
              message.success(messages('common.save.success', { name: '' }/*保存成功*/));
              this.props.close(true);
            }
          })
          .catch(e => {
            this.setState({ loading: false });
            message.error(`${messages('common.save.filed'/*保存失败*/)}，${e.response.data.message}`);
          });
      }
    });
  };

  handleDateChange = (value, key) => {
    this.setState({ [key]: value });
  };

  disabledStartDate = (startValue) => {
    const endValue = this.state.endValue;
    if (!startValue || !endValue) {
      return false;
    }
    return startValue.valueOf() > endValue.valueOf();
  };

  disabledEndDate = (endValue) => {
    const startValue = this.state.startValue;
    if (!endValue || !startValue) {
      return false;
    }
    return endValue.valueOf() <= startValue.valueOf();
  };


  handleDept = (value) => {
    let { headerData } = this.state;
    if (value && value.length && value[0].departmentId) {
      headerData.unitId = value;
      this.props.form.setFieldsValue({ unitId: value });
      this.setState({ headerData, employeeDisabled: false });
    }
  };

  //取消
  handleCancel = () => {
    let partner = this.state.partner;
    partner.disabled = true;
    this.setState({
      employeeDisabled: true,
      headerData: {},
      partner
    }, () => {
      this.props.form.resetFields();
      this.props.close();
    });
  };

  handlePartnerCategory = (value) => {
    let { headerData } = this.state;
    headerData.partnerCategory = value.key;
    this.setState({ headerData });
    if (value && value.key) {
      this.props.form.setFieldsValue({ partnerId: undefined });
    }
  };

  //渲染收款方
  renderPayeeId = () => {
    const venderParams = {
      companyOid: this.props.company.companyOID
    };
    let payeeType = this.props.form.getFieldValue('partnerCategory').key;
    return <Chooser type={payeeType === 'EMPLOYEE' ? 'bgtUser' : 'vendor_account'}
                    valueKey='id'
                    labelKey={payeeType === 'EMPLOYEE' ? 'fullName' : 'venNickname'}
                    method='get'
                    single={true}
                    itemMap
                    showClear={false}
                    placeholder={messages('common.please.select')}
                    onChange={this.selectUser}
                    listExtraParams={payeeType === 'EMPLOYEE' ? null : venderParams}/>;

  };

  selectUser = (value) => {
    let { headerData } = this.state;
    headerData.partnerId = value[0].id;
    headerData.partnerCategory === 'EMPLOYEE' ? headerData.partnerName = value[0].fullName : headerData.partnerName = value[0].venNickname;
    this.setState({ headerData });
  };


  renderUnitId = () => {
    return <Chooser type='department'
                    onChange={this.handleDept}
                    valueKey='departmentId'
                    single={true}
                    showClear={true}
                    placeholder={messages('common.please.select')}
                    labelKey='name'/>;
  };

  renderEmployeeId = () => {
    const { headerData, employeeDisabled } = this.state;
    return <Chooser type="select_authorization_user"
                    disabled={headerData.unitId ? false : employeeDisabled}
                    onChange={this.handleEmployeeId}
                    single={true}
                    showClear={true}
                    valueKey="userId"
                    placeholder={messages('common.please.select')}
                    labelKey="userName"
                    listExtraParams={{ departmentId: headerData.unitId && headerData.unitId[0].departmentId }}/>;

  };

  handleEmployeeId = (value) => {
    let { headerData } = this.state;
    headerData.employeeId = value[0] ? value[0].userId : void 0;
    headerData.userName = value[0] ? value[0].userName : void 0;
    this.setState({ headerData });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, headerData, partnerCategoryOptions, startValue, endValue, showSelectEmployeeGroup, chosenEmployeeIDs } = this.state;
    const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 10, offset: 1 } };
    let autoPartnerId = [];
    switch (headerData.partnerCategory) {
      case 'EMPLOYEE':
        headerData.partnerId
          ? autoPartnerId.push({ id: headerData.partnerId, fullName: headerData.partnerName })
          : autoPartnerId = undefined;
        break;
      case 'VENDER':
        headerData.partnerId
          ? autoPartnerId.push({ id: headerData.partnerId, venNickname: headerData.partnerName })
          : autoPartnerId = undefined;
        break;
      default:
        autoPartnerId = undefined;
        break;
    }

    return (
      <div className="new-contract-type">
        <div className="common-item-title">{messages('pre.payment.essential.information')/*基本信息*/}</div>

        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('my.contract.contractCompany')}>
            {getFieldDecorator('companyId', {
              rules: [{
                required: true,
              }],
              initialValue: headerData.companyName
            })(<Input disabled/>)}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('my.contract.name')}>
            {getFieldDecorator('contractName', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }],
              initialValue: headerData.contractName
            })(<Input placeholder={messages('common.please.enter')}/>)}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('my.contract.signDate')}>
            {getFieldDecorator('signDate', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }],
              initialValue: headerData.contractName ? moment(headerData.signDate) : null
            })(
              <DatePicker style={{ width: '100%' }} placeholder={messages('common.please.enter')}/>
            )}
          </FormItem>

          <div className="common-item-title">{messages('my.contract.party.info')}</div>

          <FormItem {...formItemLayout} label={messages('my.contract.partner.category')}>
            {getFieldDecorator('partnerCategory', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              },
                {
                  validator: (item, value, callback) => {
                    if (!value.key) {
                      callback(messages('common.please.select'));
                    }
                    callback();
                  }
                }
              ],
              initialValue: {
                key: headerData.partnerCategory,
                label: headerData.partnerCategoryName
              }
            })(
              <Select
                labelInValue
                onChange={() => this.handlePartnerCategory}
                onFocus={partnerCategoryOptions.length === 0 ? this.getContractType : () => {}}
                placeholder={messages('common.please.select')}>
                {partnerCategoryOptions
                  .map(item => <Option key={item.code}>{item.messageKey}</Option>)}
              </Select>
            )}
          </FormItem>

          {this.props.params.flag &&
          <FormItem {...formItemLayout} label={messages('my.contract.partner.name')}>
            {getFieldDecorator('partnerId', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              },
                {
                  validator: (item, value, callback) => {
                    if (!value || !value[0].id) {
                      callback(messages('common.please.select'));
                    }
                    callback();
                  }
                }
              ],
              initialValue: autoPartnerId
            })(
              this.renderPayeeId()
            )}
          </FormItem>
          }

          <div className="common-item-title">{messages('supplier.management.otherInfo')}</div>

          <FormItem {...formItemLayout} label={messages('my.contract.responsible.department')}>
            {getFieldDecorator('unitId', {
              initialValue: headerData.unitId ? [{
                departmentId: headerData.unitId,
                name: headerData.unitName
              }] : undefined
            })(
              this.renderUnitId()
            )}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('my.contract.responsible.person')}>
            {getFieldDecorator('employeeId', {
              initialValue: headerData.contractName && headerData.employeeId ? [{
                userId: headerData.employeeId,
                userName: headerData.userName
              }] : undefined
            })(
              this.renderEmployeeId()
            )}
          </FormItem>

          <FormItem {...formItemLayout} label={messages('my.limit.time')}>
            {getFieldDecorator('startDate', {
              initialValue: headerData.contractName && headerData.startDate ? moment(headerData.startDate) : startValue
            })(
              <DatePicker
                disabledDate={this.disabledStartDate}
                style={{ width: '47%' }} placeholder={messages('my.date.from')}
                onChange={(value) => this.handleDateChange(value, 'startValue')}/>
            )}
            {getFieldDecorator('endDate', {
              initialValue: headerData.contractName && headerData.endDate ? moment(headerData.endDate) : endValue
            })(
              <DatePicker
                disabledDate={this.disabledEndDate}
                style={{ width: '47%', marginLeft: '6%' }} placeholder={messages('my.date.to')}
                onChange={(value) => this.handleDateChange(value, 'endValue')}/>
            )}
          </FormItem>

          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')}</Button>
            <Button onClick={this.handleCancel}>{messages('common.cancel')}</Button>
          </div>
        </Form>

        <SelectEmployeeGroup visible={showSelectEmployeeGroup}
                             onCancel={this.handleSelectEmployeeCancel}
                             onOk={this.handleSelectEmployeeOk}
                             selectedData={chosenEmployeeIDs}/>
      </div>
    );
  }
}

NewContractType.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    main: state.main,
    company: state.login.company
  };
}

const wrappedNewContractType = Form.create()(NewContractType);

export default connect(mapStateToProps, null, null, { withRef: true })(wrappedNewContractType);
